#!/usr/bin/env node

/**
 * RickPan Electron构建脚本
 * 用于构建和打包Electron应用
 */

const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
}

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`)
}

function logStep(step, message) {
  log(`[${step}] ${message}`, 'cyan')
}

function logSuccess(message) {
  log(`✅ ${message}`, 'green')
}

function logError(message) {
  log(`❌ ${message}`, 'red')
}

function logWarning(message) {
  log(`⚠️  ${message}`, 'yellow')
}

// 检查必要的文件和目录
function checkPrerequisites() {
  logStep('检查', '验证构建环境...')
  
  const requiredFiles = [
    'package.json',
    'electron/main.ts',
    'electron/preload.ts',
    'electron-builder.json'
  ]
  
  const missingFiles = requiredFiles.filter(file => !fs.existsSync(file))
  
  if (missingFiles.length > 0) {
    logError(`缺少必要文件: ${missingFiles.join(', ')}`)
    process.exit(1)
  }
  
  logSuccess('构建环境检查通过')
}

// 清理构建目录
function cleanBuildDirs() {
  logStep('清理', '清理构建目录...')
  
  const dirsToClean = ['dist', 'dist-electron', 'release']
  
  dirsToClean.forEach(dir => {
    if (fs.existsSync(dir)) {
      fs.rmSync(dir, { recursive: true, force: true })
      log(`已清理: ${dir}`, 'yellow')
    }
  })
  
  logSuccess('构建目录清理完成')
}

// 安装依赖
function installDependencies() {
  logStep('依赖', '检查并安装依赖...')
  
  try {
    execSync('npm ci', { stdio: 'inherit' })
    logSuccess('依赖安装完成')
  } catch (error) {
    logError('依赖安装失败')
    console.error(error.message)
    process.exit(1)
  }
}

// 构建Vue应用
function buildVueApp() {
  logStep('构建', '构建Vue应用...')
  
  try {
    execSync('npm run build', { stdio: 'inherit' })
    logSuccess('Vue应用构建完成')
  } catch (error) {
    logError('Vue应用构建失败')
    console.error(error.message)
    process.exit(1)
  }
}

// 构建Electron应用
function buildElectronApp() {
  logStep('构建', '构建Electron应用...')
  
  try {
    const platform = process.argv.includes('--all') ? '' : `--${process.platform}`
    const command = `electron-builder ${platform} --publish=never`
    
    execSync(command, { stdio: 'inherit' })
    logSuccess('Electron应用构建完成')
  } catch (error) {
    logError('Electron应用构建失败')
    console.error(error.message)
    process.exit(1)
  }
}

// 显示构建结果
function showBuildResults() {
  logStep('结果', '构建结果:')
  
  const releaseDir = path.join(process.cwd(), 'release')
  
  if (fs.existsSync(releaseDir)) {
    const files = fs.readdirSync(releaseDir)
    
    if (files.length > 0) {
      log('\n构建产物:', 'bright')
      files.forEach(file => {
        const filePath = path.join(releaseDir, file)
        const stats = fs.statSync(filePath)
        const size = (stats.size / 1024 / 1024).toFixed(2)
        log(`  📦 ${file} (${size} MB)`, 'green')
      })
    } else {
      logWarning('release目录为空')
    }
  } else {
    logWarning('未找到release目录')
  }
}

// 主构建流程
function main() {
  const startTime = Date.now()
  
  log('\n🚀 开始构建RickPan Electron应用\n', 'bright')
  
  try {
    // 检查构建环境
    checkPrerequisites()
    
    // 清理构建目录
    if (process.argv.includes('--clean')) {
      cleanBuildDirs()
    }
    
    // 安装依赖
    if (process.argv.includes('--install')) {
      installDependencies()
    }
    
    // 构建Vue应用
    buildVueApp()
    
    // 构建Electron应用
    buildElectronApp()
    
    // 显示构建结果
    showBuildResults()
    
    const endTime = Date.now()
    const duration = ((endTime - startTime) / 1000).toFixed(2)
    
    log(`\n🎉 构建完成! 耗时: ${duration}秒\n`, 'bright')
    
  } catch (error) {
    logError(`构建失败: ${error.message}`)
    process.exit(1)
  }
}

// 显示帮助信息
function showHelp() {
  log('\nRickPan Electron构建脚本\n', 'bright')
  log('用法:', 'cyan')
  log('  node scripts/build-electron.js [选项]\n')
  log('选项:', 'cyan')
  log('  --clean     清理构建目录')
  log('  --install   重新安装依赖')
  log('  --all       构建所有平台')
  log('  --help      显示帮助信息\n')
  log('示例:', 'cyan')
  log('  node scripts/build-electron.js --clean --install')
  log('  node scripts/build-electron.js --all\n')
}

// 处理命令行参数
if (process.argv.includes('--help') || process.argv.includes('-h')) {
  showHelp()
  process.exit(0)
}

// 运行主流程
main()
